<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="4">
        <el-input v-model="configKeyWord" placeholder="请输入桶名" clearable />
        <el-form :inline="true" style="margin-top:20px">
          <el-button type="primary" size="mini" icon="el-icon-plus" @click="showTencentSetting">新增</el-button>
          <el-button type="danger" size="mini" icon="el-icon-delete">删除</el-button>
        </el-form>
        <el-table
          ref="configTable"
          :data="configData"
          highlight-current-row
          style="width: 100%;margin-top:15px"
          @row-click="handConfigClick"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="bucket" label="桶名" width="width" />
          <el-table-column label="配置" width="80px" tencentgn="center">
            <template slot-scope="{ row }">
              <el-button type="warning" icon="el-icon-s-tools" size="mini" @click="showTencentSetting(row)" />
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="20">
        <!-- 搜索表单 -->
        <el-form :inline="true" class="search-component">
          <el-form-item label="文件名">
            <el-input v-model="searchCondition.keyWord" placeholder="请输入文件名" clearable />
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="searchCondition.createTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              tencentgn="right"
            />
          </el-form-item>
          <el-button type="primary" icon="el-icon-search" size="medium" @click="initCloudTable">搜索</el-button>
          <el-button type="warning" icon="el-icon-refresh" size="medium" @click="resetSearchCondition">重置</el-button>
        </el-form>
        <!-- 操作按钮 -->
        <el-form :inline="true" class="operation-component">
          <el-button
            type="primary"
            icon="el-icon-upload"
            size="mini"
            @click="showAddCloudForm"
          >上&nbsp;&nbsp;&nbsp;&nbsp;传</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteCloud">批量删除</el-button>
          <el-button type="success" icon="el-icon-download" size="mini" @click="exportCloud">批量导出</el-button>

        </el-form>
        <!-- 列表 -->
        <el-table
          ref="cloudTable"
          :data="tableData"
          highlight-current-row
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" label="文件名">
            <template slot-scope="{row}">
              <el-popover
                :content="'file/' + row.type + '/' + row.realName"
                placement="top-start"
                title="路径"
                width="200"
                trigger="hover"
              >
                <a
                  slot="reference"
                  :href="'http://cloudhost:8080' + '/file/' + row.type + '/' + row.realName"
                  class="el-link--primary"
                  style="word-break:keep-all;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color: #1890ff;font-size: 13px;"
                  target="_blank"
                >
                  {{ row.name }}
                </a>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column prop="suffix" label="文件类型" />
          <el-table-column prop="size" label="大小" />
          <el-table-column prop="updateBy" label="操作人" />
          <el-table-column prop="updateTime" label="操作时间" width="width" sortable />
          <el-table-column label="操作" width="width" tencentgn="center">
            <template slot-scope="{ row }">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="small"
                :disabled="row.cloudId === 1"
                @click="deleteCloud(row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-pagination
          :current-page="page.current"
          :total="page.total"
          :page-size="page.size"
          :page-sizes="[10, 20, 50, 100]"
          style="padding: 20px 0"
          layout="total,prev, pager, next, sizes,jumper"
          @current-change="initCloudTable"
          @size-change="handleSizeChange"
        />
        <!-- 新增/修改表单 -->
        <el-dialog :title="cloud.id ? '修改文件' : '上传文件'" :visible.sync="dialogFormVisible" width="20%">
          <el-form ref="cloudForm" :model="cloud" label-width="80px">
            <!--   上传文件   -->
            <el-form-item v-if="!cloud.id" label="上传">
              <el-upload
                ref="upload"
                drag
                :limit="1"
                :before-upload="beforeUpload"
                :auto-upload="false"
                :headers="headers"
                :on-success="handleSuccess"
                :on-error="handleError"
                :action="tencentUploadApi + '?name=' + cloud.name + '&configId=' + searchCondition.tencentConfigId"
              >
                <div class="eladmin-upload"><i class="el-icon-upload" /> </div>
                <div style="color:#1890ff">添加文件</div>
                <div slot="tip" class="el-upload__tip">可上传任意格式文件，但不可超过10M</div>
              </el-upload>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button v-if="!cloud.id" type="primary" @click="upload">确 定</el-button>
            <el-button v-else type="primary" @click="saveDialogForm">确 定</el-button>
          </div>
        </el-dialog>
        <!-- 阿里云配置表单 -->
        <el-dialog :visible.sync="dialog" :close-on-click-modal="false" title="阿里云配置" append-to-body width="580px">
          <el-form ref="form" :model="config" :rules="rules" style="margin-top: 6px;" size="small" label-width="110px">
            <el-form-item label="空间名称" prop="bucket">
              <el-input v-model="config.bucket" style="width: 95%;" placeholder="存储空间名称作为唯一的 Bucket 识别符" />
            </el-form-item>
            <el-form-item label="region">
              <el-select v-model="config.region" placeholder="请选择region">
                <el-option v-for="item in regions" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item label="Secret Id" prop="secretId">
              <el-input v-model="config.secretId" style="width: 95%" placeholder="secretId，在安全中心，秘钥管理中查看" />
            </el-form-item>
            <el-form-item label="Secret Key" prop="secretKey">
              <el-input
                v-model="config.secretKey"
                type="password"
                style="width: 95%;"
                placeholder="secretKey，在安全中心，秘钥管理中查看"
              />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialog = false">取消</el-button>
            <el-button :loading="loading" type="primary" @click="createOrUpdateTencentConfig">确认</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Config from '@/settings'
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'
export default {
  name: 'TencentStorage',
  data() {
    return {
      page: {
        total: 0, // 总记录数
        current: 1, // 当前页码
        size: 10, // 每页记录数
        orders: [{ column: 'id', asc: true }]
      },
      searchCondition: {
        createTime: [],
        keyWord: '',
        tencentConfigId: undefined
      },
      tableData: [], // 列表数据
      configData: [], // 配置列表
      configKeyWord: '',
      dialogFormVisible: false, // 是否展示新增/修改表单
      selectedIds: [], // 所有选择的id的数组
      cloud: {
        id: undefined,
        name: ''
      }, // 当前要操作的cloud
      regions: ['北京', '南京', '上海', '广州', '成都', '重庆'],
      dialog: false,
      loading: false,
      config: {
        secretId: '',
        secretKey: '',
        bucket: '',
        region: ''
      },
      rules: {
        secretId: [
          { required: true, message: '请输入secretId', trigger: 'blur' }
        ],
        secretKey: [
          { required: true, message: '请输入secretKey', trigger: 'blur' }
        ],
        bucket: [
          { required: true, message: '请输入空间名称', trigger: 'blur' }
        ],
        region: [
          { required: true, message: '请输入region', trigger: 'blur' }
        ]
      },
      headers: { 'Authorization': getToken() }
    }
  },
  mounted() {
    this.initCloudTable()
  },
  // eslint-disable-next-line vue/order-in-components
  computed: {
    ...mapGetters([
      'baseApi',
      'tencentUploadApi'
    ])
  },
  methods: {
    async initCloudTable(current = 1) {
      const { page, searchCondition } = this
      if (Number.isInteger(current)) {
        page.current = current
      }
      const configResult = await this.$API.tencentConfig.pageQuery(this.configKeyWord)
      if (configResult.code === 200) {
        if (configResult.data) {
          this.configData = configResult.data
          if (searchCondition.tencentConfigId) {
            const result = await this.$API.tencentContent.pageQuery({ searchCondition, page })
            if (result.code === 200) {
              this.tableData = result.data.records
              this.page.current = result.data.current
              this.page.size = result.data.size
              this.page.total = result.data.total
            }
          } else if (configResult.data[0]) {
            this.searchCondition.tencentConfigId = configResult.data[0].id
            const result = await this.$API.tencentContent.pageQuery({ searchCondition, page })
            if (result.code === 200) {
              this.tableData = result.data.records
              this.page.current = result.data.current
              this.page.size = result.data.size
              this.page.total = result.data.total
            }
          }
        }
      }
    },
    async handConfigClick(row) {
      const { page, searchCondition } = this
      searchCondition.tencentConfigId = row.id
      const result = await this.$API.tencentContent.pageQuery({ searchCondition, page })
      if (result.code === 200) {
        this.tableData = result.data.records
        this.page.current = result.data.current
        this.page.size = result.data.size
        this.page.total = result.data.total
      }
    },
    resetSearchCondition() {
      this.searchCondition.createTime = []
      this.searchCondition.keyWord = ''
      this.initCloudTable()
    },
    async createOrUpdateTencentConfig() {
      if (this.config.id) {
        const result = await this.$API.tencentConfig.updateTencentConfig(this.config)
        if (result.code === 200) {
          this.$message({
            message: '修改成功',
            type: 'success',
            showClose: true,
            duration: Config.duration
          })
          this.initCloudTable()
          this.dialog = false
        } else {
          this.$message({
            message: '修改失败',
            type: 'error',
            showClose: true,
            duration: Config.duration
          })
        }
      } else {
        const result = await this.$API.tencentConfig.createTencentConfig(this.config)
        if (result.code === 200) {
          this.$message({
            message: '保存成功',
            type: 'success',
            showClose: true,
            duration: Config.duration
          })
          this.initCloudTable()
          this.dialog = false
        } else {
          this.$message({
            message: '保存失败',
            type: 'error',
            showClose: true,
            duration: Config.duration
          })
        }
      }
    },
    async deleteCloud(row) {
      let cloudIds = []
      if (row.id) {
        cloudIds = [row.id]
      } else {
        cloudIds = this.selectedIds
      }
      if (cloudIds.length === 0) {
        this.$message({
          message: '请选择要操作的数据',
          type: 'warning',
          showClose: true,
          duration: Config.duration
        })
        return
      }
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          console.log(this.searchCondition.tencentConfigId)
          const result = await this.$API.tencentContent.deleteTencentContent(cloudIds, this.searchCondition.tencentConfigId)
          if (result.code === 200) {
            this.$message({
              message: '删除成功',
              type: 'success',
              showClose: true,
              duration: Config.duration
            })
            this.initCloudTable()
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
            showClose: true,
            duration: Config.duration
          })
        })
    },
    async showAddCloudForm() {
      if (!this.searchCondition.tencentConfigId) {
        this.$message({
          message: '请先添加相应配置，再操作',
          type: 'warning',
          showClose: true,
          duration: Config.duration
        })
        return false
      }
      this.cloud.name = ''
      this.dialogFormVisible = true
    },
    async showUpdateCloudForm(row) {
      this.cloud.id = row.id
      this.cloud.name = row.name
      this.dialogFormVisible = true
    },
    upload() {
      this.$refs.upload.submit()
    },
    /*
        列表选中状态发生改变的监听回调
      */
    handleSelectionChange(selection) {
      this.selectedIds = selection.map((item) => item.id)
    },
    /*
      处理pageSize发生改变的监听回调
      */
    handleSizeChange(pageSize) {
      this.page.size = pageSize
      this.initCloudTable()
    },
    async exportCloud() {
      await this.$API.tencentContent.exportCloud(this.selectedIds)
    },
    handleSuccess() {
      this.$message({
        message: '上传成功',
        type: 'success',
        showClose: true,
        duration: Config.duration
      })
      this.$refs.upload.clearFiles()
      this.initCloudTable()
      this.dialogFormVisible = false
    },
    handleError() {
      this.$message({
        message: '上传失败',
        type: 'error',
        showClose: true,
        duration: Config.duration
      })
    },
    beforeUpload(file) {
      let isLt2M = true
      isLt2M = file.size / 1024 / 1024 < 100
      if (!isLt2M) {
        this.loading = false
        this.$message({
          message: '上传文件大小不能超过 10MB!',
          type: 'error',
          showClose: true,
          duration: Config.duration
        })
      }
      this.cloud.name = file.name
      return isLt2M
    },
    async showTencentSetting(row) {
      if (row.id) {
        const result = await this.$API.tencentConfig.getTencentConfig(row.id)
        if (result.code === 200) {
          this.config = result.data
          this.dialog = true
        } else {
          this.$message({
            message: '获取配置失败',
            type: 'error',
            showClose: true,
            duration: Config.duration
          })
        }
      } else {
        this.config = {
          accessKey: '',
          secretKey: '',
          bucket: '',
          region: ''
        }
        this.dialog = true
      }
    }
  }
}
</script>

<style scoped>

</style>

